/**
 * 创建节点模板 暂时未使用
 * @param panel
 * @param graph
 * @param name
 * @param icon
 * @param style
 * @param width
 * @param height
 * @param value
 * @param parentNode
 */
function insertEdgeTemplate(panel, graph, name, icon, style, width, height, value, parentNode){
		var cells = [new mxCell((value != null) ? value : '', new mxGeometry(0, 0, width, height), style)];
		cells[0].geometry.setTerminalPoint(new mxPoint(0, height), true);
		cells[0].geometry.setTerminalPoint(new mxPoint(width, 0), false);
		cells[0].edge = true;
		var funct = function(graph, evt, target){
			cells = graph.getImportableCells(cells);
			if(cells.length > 0){
				var validDropTarget = (target != null) ? graph.isValidDropTarget(target, cells, evt) : false;
				var select = null;
				if(target != null && !validDropTarget){
					target = null;
				}
				var pt = graph.getPointForEvent(evt);
				var scale = graph.view.scale;
				pt.x -= graph.snap(width / 2);
				pt.y -= graph.snap(height / 2);
				select = graph.importCells(cells, pt.x, pt.y, target);
				GraphEditor.edgeTemplate = select[0];
				graph.scrollCellToVisible(select[0]);
				graph.setSelectionCells(select);
			}
		};
		var node = panel.addTemplate(name, icon, parentNode, cells);
		var installDrag = function(expandedNode){
			if (node.ui.elNode != null){
				var dragPreview = document.createElement('div');
				dragPreview.style.border = 'dashed black 1px';
				dragPreview.style.width = width+'px';
				dragPreview.style.height = height+'px';
				mxUtils.makeDraggable(node.ui.elNode, graph, funct, dragPreview, -width / 2, -height / 2,graph.autoscroll, true);
			}
		};
		if(!node.parentNode.isExpanded()){
			panel.on('expandnode', installDrag);
		}else{
			installDrag(node.parentNode);
		}
		return node;
};

/**
 * 添加元素右上角的删除图标
  * @param graph
 * @param cell
 * @param addDeleteIcon
 */
function addOverlays(graph, cell, addDeleteIcon){  
    var overlay = new mxCellOverlay(new mxImage('images/add.png', 24, 24), 'Add child');  
    overlay.cursor = 'hand';  
    overlay.align = mxConstants.ALIGN_CENTER;  
    overlay.addListener(mxEvent.CLICK, mxUtils.bind(this, function(sender, evt){  
        addChild(graph, cell);  
    }));  
    graph.addCellOverlay(cell, overlay);  
    if (addDeleteIcon){  
        overlay = new mxCellOverlay(new mxImage('images/close.png', 30, 30), 'Delete');  
        overlay.cursor = 'hand';  
        overlay.offset = new mxPoint(-4, 8);  
        overlay.align = mxConstants.ALIGN_RIGHT;  
        overlay.verticalAlign = mxConstants.ALIGN_TOP;  
        overlay.addListener(mxEvent.CLICK, mxUtils.bind(this, function(sender, evt){  
            deleteSubtree(graph, cell);  
        }));  
        graph.addCellOverlay(cell, overlay);  
    }  
};

/**
 * 添加子元素
 * @param graph
 * @param cell
 * @returns {*}
 */
function addChild(graph, cell){  
    var model = graph.getModel();  
    var parent = graph.getDefaultParent();  
    var vertex;  
    model.beginUpdate();  
    try {  
        vertex = graph.insertVertex(parent, null, 'Double click to set name');  
        var geometry = model.getGeometry(vertex);  
        var size = graph.getPreferredSizeForCell(vertex);  
        geometry.width = size.width;  
        geometry.height = size.height;  
        var edge = graph.insertEdge(parent, null, '', cell, vertex);  
        edge.geometry.x = 1;  
        edge.geometry.y = 0;  
        edge.geometry.offset = new mxPoint(0, -20);  
    }finally{  
        model.endUpdate();  
    }  
    return vertex;  
};

/**
 *
 * @param graph
 * @param history
 */
function imp(graph,history){
    graph_refresh = graph;
}

/**
 *
 * @param id
 */
function doImpl(id){

}

/**
 * 连线样式设置虚线
 * @param editor
 */
function connectEdge(editor){
	if (editor.defaultEdge != null){
		editor.defaultEdge.style = 'straightEdge';
	}
}

/**
 *
 * @param graph
 * @param history
 */
function importP(graph,history){
    //initScroll()
	console.log("importP---");
    imp(graph,history)
}

/**
 *
 * @param graph
 */
function saveP(graph){
    //initScroll()
    //获取mxgraph拓扑图数据
    //var enc = new mxCodec(mxUtils.createXmlDocument());
    //var node1 = enc.encode(graph.getModel());
    //var mxgraphxml = mxUtils.getXml(node1);
    var enc = new mxCodec(mxUtils.createXmlDocument());
    var node = enc.encode(graph.getModel());
    var mxgraphxml = mxUtils.getPrettyXml(node);
    mxgraphxml = mxgraphxml.replace(/\"/g,"'");
    //mxgraphxml = encodeURIComponent(mxgraphxml);

    var xmlDoc = mxUtils.createXmlDocument();
    var root = xmlDoc.createElement('output');
    xmlDoc.appendChild(root);
    var xmlCanvas = new mxXmlCanvas2D(root);
    var imgExport = new mxImageExport();
    imgExport.drawState(graph.getView().getState(graph.model.root), xmlCanvas);
    var bounds = graph.getGraphBounds();
    var w = Math.round(bounds.x + bounds.width + 4);
    var h = Math.round(bounds.y + bounds.height + 4);
    var imgxml = mxUtils.getXml(root);
    //imgxml = "<output>"+imgxml+"</output>";
    //imgxml = encodeURIComponent(imgxml);

    saveDesign(mxgraphxml,w,h,imgxml);
}

/**
 *
 */
function exportP(){
    console.log("----导出---");
}

/**
 *
 */
function closeJehcLcWin(){
    $('#jehcLcModal').modal('hide');
}

/**
 *
 */
function initScroll(){
    // $("#sidebarContainer").niceScroll({cursorborder:"",cursorcolor:"#e0e0e0",boxzoom:false});
    // $("#diagramContainer").niceScroll({cursorborder:"",cursorcolor:"#e0e0e0",boxzoom:false}); // First scrollable DIV
}

/**
 *
 */
function nodeScroll(){
    // $("#mportletId").niceScroll({cursorborder:"",cursorcolor:"#e0e0e0",boxzoom:false});
    // $("#mportletId1").niceScroll({cursorborder:"",cursorcolor:"#e0e0e0",boxzoom:false});
    // $("#TabCol").niceScroll({cursorborder:"",cursorcolor:"#e0e0e0",boxzoom:false});
}


/**
 *
 * @param flag
 * @param graph
 */
function linetostyle(flag,graph){
    // var line_style = basePath+'/view/pc/lc-view/lc-design/archive/grapheditor/resources/default-style.xml';
    // if(flag == 0){
    //     //如果为1直线
    //     line_style = basePath+'/view/pc/lc-view/lc-design/archive/grapheditor/resources/default-style.xml';
    // }else if(flag == 1){
    //     //如果为1曲线
    //     line_style = basePath+'/view/pc/lc-view/lc-design/archive/grapheditor/resources/bight-style.xml';
    // }
    // var history = new mxUndoManager();
    // //载入默认样式
    // var node = mxUtils.load(line_style).getDocumentElement();
    // var dec = new mxCodec(node.ownerDocument);
    // dec.decode(node, graph.getStylesheet());
    // var edgeStyle = graph.getStylesheet().getDefaultEdgeStyle();
    // //edgeStyle[mxConstants.STYLE_EDGE] = mxEdgeStyle.TopToBottom;
    // edgeStyle['gradientColor'] = '#c0c0c0';
    // edgeStyle['strokeColor'] = '#c0c0c0'; //更改连线默认样式此处为颜色
    // edgeStyle['dashed'] = '1'; //虚线
    // edgeStyle['strokeWidth'] = 0.1;
    // edgeStyle['fontSize'] = '8';
    // edgeStyle['fontColor'] = '#000';
    // edgeStyle['arrowWidth'] = 0.1;
    // graph.alternateEdgeStyle = 'elbow=vertical';
    // graph.refresh();
    // Ext.getCmp('lc_process_mxgraph_style').setValue(flag);
}

/**
 * 载入XML流程图
 * @param graph
 * @param xml
 */
function loadXml(graph,xml){
    graph.getModel().beginUpdate();
    try{
        if(xml != null && xml.length > 0){
            var doc = mxUtils.parseXml(xml);
            var dec = new mxCodec(doc);
            dec.decode(doc.documentElement, graph.getModel());
        }
    }finally{
        graph.getModel().endUpdate();
        graph.refresh();
    }
    setTimeout(function(){
        resetZxLine(graph);
    },100);
}

/**
 *
 */
$(document).ready(function() {
    $('#BaseForm').bootstrapValidator({
        message: '此值不是有效的'
    });
});

/**
 * 保存设计
 * @param mxgraphxml
 * @param w
 * @param h
 * @param imgxml
 */
function saveDesign(mxgraphxml,w,h,imgxml){
    console.log("----保存设计---");
}


/**
 * 将字符串转换XML
 * @param xmlobj
 * @returns {*}
 */
function printString(xmlobj){
    var xmlDom;
    //IE
    if(document.all){
        xmlDom=new ActiveXObject("Microsoft.XMLDOM");
        xmlDom.loadXML(xmlobj);
    }
    //非IE
    else {
        xmlDom = new DOMParser().parseFromString(xmlobj, "text/xml");
    }
    return xmlDom;
}

/**
 *
 * @param graph
 * @param reFlow
 */
function resetZxLine(graph,reFlow){
    var allLines =graph.getModel().cells;
    for(var i in allLines){
        var cell = allLines[i];
        if(cell.nodeType == "zxLine"){
            // Adds animation to edge shape and makes "pipe" visible
            graph.getModel().beginUpdate();
            try
            {
                var state = graph.view.getState(cell);
                if(null != state){
                    state.shape.node.getElementsByTagName('path')[0].removeAttribute('visibility');
                    state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke-width', '6');
                    state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke', 'lightGray');
                    state.shape.node.getElementsByTagName('path')[0].removeAttribute('class');
                    if(undefined != reFlow && reFlow == true){
                        state.shape.node.getElementsByTagName('path')[1].setAttribute('class', 'reflow');
                    }else{
                        state.shape.node.getElementsByTagName('path')[1].setAttribute('class', 'flow');
                    }

                }
            }
            finally
            {
                // Updates the display
                graph.getModel().endUpdate();
            }
        }
    }
}

/**
 *
 * @param graph
 * @param parent
 * @param x
 * @param y
 */
function aminLine(graph,parent,x,y){
    var vertexStyle = 'shape=cylinder;strokeWidth=2;fillColor=#ffffff;strokeColor=black;' +
        'gradientColor=#a0a0a0;fontColor=black;fontStyle=1;spacingTop=14;';
    graph.getModel().beginUpdate();
    try
    {
        var v1 = graph.insertVertex(parent, null, 'Pump', x, y, 48, 48,vertexStyle);
        var v2 = graph.insertVertex(parent, null, 'Tank', x+160, y, 48, 48,vertexStyle);
        var edge = graph.insertEdge(parent, null, '', v1, v2,'strokeWidth=3;endArrow=block;endSize=2;endFill=1;strokeColor=black;rounded=1;');
        edge.geometry.points = [new mxPoint(x, y)];
        graph.orderCells(true, [edge]);
    }
    finally
    {
        // Updates the display
        graph.getModel().endUpdate();
    }

    // Adds animation to edge shape and makes "pipe" visible
    var state = graph.view.getState(edge);
    // state.shape.node.getElementsByTagName('path')[0].removeAttribute('visibility');
    state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke-width', '6');
    state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke', 'lightGray');
    state.shape.node.getElementsByTagName('path')[1].setAttribute('class', 'flow');

    graph.getModel().beginUpdate();
    try
    {
        graph.removeCells([v1], false);
        graph.removeCells([v2], false);
    }
    finally
    {
        // Updates the display
        graph.getModel().endUpdate();
    }

}

/**
 *
 * @param graph
 * @param edge
 */
function addAnimationEdge(graph,edge){
    // Adds animation to edge shape and makes "pipe" visible
    graph.getModel().beginUpdate();
    try
    {
        var state = graph.view.getState(edge);
        state.shape.node.getElementsByTagName('path')[0].removeAttribute('visibility');
        state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke-width', '6');
        state.shape.node.getElementsByTagName('path')[0].setAttribute('stroke', 'lightGray');
        state.shape.node.getElementsByTagName('path')[1].setAttribute('class', 'flow');
    }
    finally
    {
        // Updates the display
        graph.getModel().endUpdate();
    }
}

/**
 *
 * @param graph
 */
function initData(graph){
    if(null != $("#graph_site_id").val() && '' != $("#graph_site_id").val()){
        ajaxBRequestCallFn(monitorModules+'/graphSite/get/'+$('#graph_site_id').val(),{},function(result){
            //操作颜色
            setTimeout(function(){
                var background = result.data.background;
                if(null != background  && '' != background){
                    ThizViewPort.editorUi.setBackgroundColor(background);//设置背景样式方法一
                }
                var gridColor = result.data.gridColor;
                var gridSize =  result.data.gridSize;
                var showGrid = result.data.showGrid;
                if(null != showGrid && showGrid == 0){
                    if(null != gridSize && '' != gridSize){
                        graph.gridSize = gridSize;// 更改布局网格大小
                    }
                    if(null != gridColor && '' != gridColor){
                        ThizViewPort.editorUi.setGridColor(gridColor);//设置网格颜色
                        // console.log("ThizViewPort.editorUi.editor.graph.view.gridColor ",ThizViewPort.editorUi.editor.graph.view.gridColor); //获取网格颜色
                    }
                }
                // ThizViewPort.editorUi.editor.graph.background = "#000"//设置背景样式方法二
                // console.log("ThizViewPort.editorUi.editor.graph.background",ThizViewPort.editorUi.editor.graph.background);//获取背景颜色
            },0);
            loadXml(graph,result.data.graph_site_mxgraph);
        });
    }
}

/**
 *
 */
$(document).ready(function(){
    var graph_site_id = GetQueryString("graph_site_id");
    $("#graph_site_id").val(graph_site_id)
});